package com.leyou.filter;

import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.config.FilterProperties;
import com.leyou.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.ZuulFilterResult;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by 冯金平 on 2023/3/19 19:45
 */
@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class LoginFilter extends ZuulFilter {
    @Autowired
    private JwtProperties properties;
    @Autowired
    private FilterProperties filterProperties;
    /**
     * 过滤器类型
     *
     * @return {@link String}
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器顺序
     *
     * @return int
     */
    @Override
    public int filterOrder() {
        return 10;
    }

    /**
     * 判断什么被过滤-过滤器
     *
     * @return boolean
     */
    @Override
    public boolean shouldFilter() {
        //上下文环境
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String url = request.getRequestURL().toString();
        //请求路径中是否包含白名单，uri是一个完整的www.leyou.com/api/auth/accredit
        List<String> allowPaths = filterProperties.getAllowPaths();
        for (String allowPath : allowPaths) {
            if (StringUtils.contains(url, allowPath)){
                return false;//不再拦截
            }
        }

        return true;//非白名单
    }

    /**
     * 过滤器具体方法
     *
     * @return {@link Object}
     * @throws ZuulException zuul例外
     */
    @Override
    public Object run() throws ZuulException {
        //上下文环境
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        //获取token
        String token = CookieUtils.getCookieValue(request, this.properties.getCookieName());
        //校验
        try {
            JwtUtils.getInfoFromToken(token,this.properties.getPublicKey());

        } catch (Exception e) {
            //认证失败
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            e.printStackTrace();
        }

        return null;
    }
}
